/*
 * @Author: yangzonglong
 * @Date: 2020-05-29 10:12:12
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-09-22 11:31:47
 * @Auditor:
 */
import React from "react";
import { FormatProps, SelectedRowKeys, ColumnProps } from "./interface";
import moment from "moment";
import { Switch } from "antd";

export const ROW_HEIGHT = 37;
export const TOOLBAR_HEIGHT = 60;
export const __Sorter__ = '__Sorter__';

const t = window.$app.t;

export function typeToText(type: any) {
  if (typeof type === "boolean") return type ? t("yes") : t("no");
  return type;
}

export function moneyFormat(text: string | number | undefined) {
  if (!text && text !== 0) return "";
  try {
    let num = typeof text === "string" ? parseFloat(text) : text;
    return num
      .toFixed(2)
      .toString()
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  } catch (error) {
    console.log(error);
    return "0.00";
  }
}

export function getVisibleHeight(height: number, len: number) {
  const bodyHeight = height - ROW_HEIGHT; // 获取 table body高度
  const listHeight = len * ROW_HEIGHT; // 当前list 占用总高度

  return listHeight > bodyHeight ? bodyHeight : undefined;
}

export const textToNumberFormat = moneyFormat; // 兼容旧的引用

export function formatRenderText(
  text: string | number | undefined,
  format: FormatProps
) {
  if ((!text && text !== 0) || !format) return text;
  if (format === "time" && text)
    return moment(text).format(window.$app.MOMENT_FORMAT_TIME);
  if (format === "date" && text)
    return moment(text).format(window.$app.MOMENT_FORMAT_DATE);
  if (format === "money") return moneyFormat(text);
  if (format === "switch") return <Switch size="small" checked={!!text} />;
  return text;
}

export function flatSelectedRowKeys(selectedRowKeys: SelectedRowKeys) {
  return Object.keys(selectedRowKeys).reduce((next: string[], cur) => {
    next = next.concat(selectedRowKeys[cur]);
    return next;
  }, []);
}

export function handleSelectedRows(
  selectedRows: any[],
  originalSelectRows: any[],
  rowKey: string
) {
  const idMap = originalSelectRows.reduce(
    (next, cur) => (next[cur[rowKey]] = true) && next,
    {}
  );
  return originalSelectRows.concat(
    selectedRows.filter((item) => !idMap[item[rowKey]])
  );
}

export function getSelectedRows(
  selectedRowKeys: SelectedRowKeys,
  selectRows: any[],
  rowKey: string
) {
  const flatRowKey = flatSelectedRowKeys(selectedRowKeys);
  return selectRows.filter((item) => flatRowKey.includes(item[rowKey]));
}

export function removeSelectedRowKeys(
  rowKeys: string[],
  selectedRowKeys: SelectedRowKeys
) {
  Object.keys(selectedRowKeys).forEach((page) => {
    selectedRowKeys[page] = selectedRowKeys[page].filter(
      (rowKey: string) => !rowKeys.includes(rowKey)
    );
  });
  return { ...selectedRowKeys };
}

export function handSorter(column: ColumnProps<any>) {
  return (rowA: any, rowB: any) => {
    const dataIndex = column.dataIndex as string;
    let res;
    let a = rowA[dataIndex] ?? '',
      b = rowB[dataIndex] ?? '';
    if (a === b) {
      res = 0;
    } else if (typeof a === 'number' && typeof b === 'number') {
      res = a > b ? 1 : -1;
    } else {
      a = a + '';
      b = b + '';
      res = a.toUpperCase?.().localeCompare(b.toUpperCase?.(), undefined, { numeric: true });
    }
    return res;
  };
}

export const CURR_PAGE_SIZE = 'CURR_PAGE_SIZE';
export const CURR_COLUMN_WIDTH = 'CURR_COLUMN_WIDTH';

export function getColumnWidth(uuid: string, key: string = CURR_COLUMN_WIDTH) {
  const widthsStr = window.sessionStorage.getItem(key);
  if (widthsStr) {
    const widths = JSON.parse(widthsStr || '{}');
    const width = widths[uuid];
    if (width && width > 0) return +width;
  }
}
export function setColumnsWidth(uuid: string, width: number, key: string = CURR_COLUMN_WIDTH) {
  const widthsStr = window.sessionStorage.getItem(key);
  if (widthsStr) {
    const widths = JSON.parse(widthsStr || '{}');
    window.sessionStorage.setItem(
      key,
      JSON.stringify({
        ...widths,
        [uuid]: width
      })
    );
  } else {
    window.sessionStorage.setItem(key, JSON.stringify({ [uuid]: width }));
  }
}

export const formTagNames = ["INPUT", "SELECT"];

export function _setSorterKey(sorter: Partial<{ column: any; field: string; order: string; }> = {}, identify: string) {
  const w = window as any;
  if (!w[__Sorter__]) w[__Sorter__] = {};
  w[__Sorter__][identify] = { [sorter.field!]: sorter }; // 一个Table暂时只做一个字段排序
  return w[__Sorter__];
}
export function _getSorterKey(dataIndex: string, identify: string) {
  return (window as any)[__Sorter__]?.[identify]?.[dataIndex]?.order;
}
